//
//  NSObject+Extension.m
//  RunTime
//
//  Created by zhang_rongwu on 16/3/3.
//  Copyright © 2016年 zhang_rongwu. All rights reserved.
//

#import "NSObject+Extension.h"
#import <objc/runtime.h>
@implementation NSObject (Extension)

+ (void)swizzleClassMethod:(Class)class1 originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
    Method otherMehtod = class_getClassMethod(class1, otherSelector);
    Method originMehtod = class_getClassMethod(class1, originSelector);
    method_exchangeImplementations(otherMehtod, originMehtod);
}

+ (void)swizzleInstanceMethod:(Class)class1 originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
    Method otherMehtod = class_getInstanceMethod(class1, otherSelector);
    Method originMehtod = class_getInstanceMethod(class1, originSelector);
    method_exchangeImplementations(otherMehtod, originMehtod);
}

+ (void)swizzleMethod:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector {
    Class class = [self class];

    //原有方法
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    //替换原有方法的新方法
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    //先尝试給源SEL添加IMP，这里是为了避免源SEL没有实现IMP的情况
    BOOL didAddMethod = class_addMethod(class,originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {//添加成功：说明源SEL没有实现IMP，将源SEL的IMP替换到交换SEL的IMP
        class_replaceMethod(class,swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {//添加失败：说明源SEL已经有IMP，直接将两个SEL的IMP交换即可
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

@end

//@implementation NSArray(Extension)
//+ (void)load
//{
//    [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayI") originSelector:@selector(objectAtIndex:) otherSelector:@selector(WRObjectAtIndex:)];
//}
//
//- (id)WRObjectAtIndex:(NSUInteger)index
//{
//    if (index < self.count) {
//        return [self WRObjectAtIndex:index];
//    } else {
//        return nil;
//    }
//}
//@end

//@implementation NSMutableArray(Extension)

//+ (void)load {
//    [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayM") originSelector:@selector(addObject:) otherSelector:@selector(WRAddObject:)];
//    [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayM") originSelector:@selector(objectAtIndex:) otherSelector:@selector(WRObjectAtIndex:)];
//}
//
//- (void)WRAddObject:(id)object
//{
//    if (object != nil) {
//        [self WRAddObject:object];
//    }
//}
//
//- (id)WRObjectAtIndex:(NSUInteger)index
//{
//    if (index < self.count) {
//        return [self WRObjectAtIndex:index];
//    } else {
//        return nil;
//    }
//}
//@end







